frappe.utils Functions Reference Guide

User Information Functions

Function: get_fullname(user=None)

Description: Returns the full name (first name + last name) of a user from the User DocType.

Parameters:

  • user (str, optional): The user ID. Defaults to the currently logged-in user.

Example Usage:

fullname = get_fullname("admin@example.com")

Function: get_email_address(user=None)

Description: Retrieves the email address associated with the user.

Parameters:

  • user (str, optional): User ID. Defaults to current session user.

Example Usage:

email = get_email_address("admin@example.com")

Function: get_formatted_email(user, mail=None)

Description: Returns a formatted string with full name and email in the format John Doe <john@example.com>.

Parameters:

  • user (str): User ID.
  • mail (str, optional): Override email address.

Example Usage:

formatted = get_formatted_email("admin@example.com")

Email Utilities

Function: extract_email_id(email)

Description: Extracts only the email part from a formatted email string.

Parameters:

  • email (str): Formatted or raw email string.

Example Usage:

email_id = extract_email_id("John Doe <john@example.com>")

Function: split_emails(txt)

Description: Splits a string of emails into a list, handling commas and line breaks.

Parameters:

  • txt (str): Multi-email string.

Example Usage:

emails = split_emails("a@example.com, b@example.com\nc@example.com")

Function: sanitize_email(emails)

Description: Validates and formats a list of emails into safe Full Name <email> format.

Parameters:

  • emails (str): String of emails.

Example Usage:

clean = sanitize_email("a@example.com, b@example.com")

Validation Functions

Function: validate_phone_number_with_country_code(phone_number, fieldname)

Description: Validates a phone number using country code parsing.

Parameters:

  • phone_number (str): Phone number to validate.
  • fieldname (str): Name of the field in the form.

Example Usage:

validate_phone_number_with_country_code("+255712345678", "contact_number")

Function: validate_phone_number(phone_number, throw=False)

Description: Checks whether a phone number is valid. Can raise an exception.

Parameters:

  • phone_number (str): Phone number.
  • throw (bool): Raise exception if invalid.

Example Usage:

if validate_phone_number("+255712345678"):
    print("Valid")

Function: validate_email_address(email_str, throw=False)

Description: Validates email address format.

Parameters:

  • email_str (str): Email string.
  • throw (bool): Raise exception if invalid.

Example Usage:

valid = validate_email_address("user@example.com")

Function: validate_name(name, throw=False)

Description: Validates personal name formats.

Parameters:

  • name (str): Name string.
  • throw (bool): Raise exception if invalid.

Example Usage:

validate_name("John O'Reilly")

Function: validate_url(txt, throw=False, valid_schemes=None)

Description: Validates if the given string is a URL. Optionally enforces scheme.

Parameters:

  • txt (str): URL string.
  • throw (bool): Raise exception on invalid URL.
  • valid_schemes (list or str, optional): Acceptable schemes like "http", "https".

Example Usage:

validate_url("https://frappe.io", throw=True)

Markdown & HTML Utilities

Function: strip_html_tags(text)

Description: Removes all HTML tags from a given string.

Parameters:

  • text (str): HTML content.

Example Usage:

clean = strip_html_tags("<p>Hello</p>")

Function: markdown(text, sanitize=True, linkify=True)

Description: Converts markdown or plain text to sanitized HTML.

Parameters:

  • text (str): Markdown or HTML text.
  • sanitize (bool): Clean HTML output.
  • linkify (bool): Convert URLs to links.

Example Usage:

html = markdown("# Welcome\nVisit https://frappe.io")

Function: is_markdown(text)

Description: Detects whether a string is markdown.

Parameters:

  • text (str): Text content.

Example Usage:

is_md = is_markdown("# Heading")

File & Path Utilities

Function: get_path(*path, **kwargs)

Description: Joins a list of paths using the site path as the base.

Parameters:

  • *path: List of path parts.
  • base (str, optional): Override base path.

Example Usage:

path = get_path("public", "files")

Function: get_site_path(*path)

Description: Joins paths under the current site's base directory.

Parameters:

  • *path: Path parts.

Example Usage:

site_path = get_site_path("public")

Function: get_files_path(*path, is_private=False)

Description: Returns full path under public or private files.

Parameters:

  • *path: File path parts.
  • is_private (bool): Use private path.

Example Usage:

private_path = get_files_path("invoice.pdf", is_private=True)

Function: get_file_size(path, format=False)

Description: Returns file size in bytes or human-readable format.

Parameters:

  • path (str): File path.
  • format (bool): Return in readable units (KB, MB).

Example Usage:

size = get_file_size("/path/to/file", format=True)

Function: get_file_timestamp(fn)

Description: Returns the last modified timestamp of a file.

Parameters:

  • fn (str): File path.

Example Usage:

ts = get_file_timestamp("example.txt")

Shell Execution Utilities

Function: execute_in_shell(cmd, verbose=False, low_priority=False, check_exit_code=False)

Description: Executes a shell command and returns standard output and error output.

Parameters:

  • cmd (str or list): The shell command to execute.
  • verbose (bool): Print the output if True.
  • low_priority (bool): Run the command with lower priority.
  • check_exit_code (bool): Raise exception if the command fails.

Example Usage:

err, out = execute_in_shell("ls -la", verbose=True)

Function: touch_file(path)

Description: Updates the modification time of a file or creates it if it does not exist.

Parameters:

  • path (str): Path to the file.

Example Usage:

touch_file("temp.log")

JSON & Data Utilities

Function: parse_json(val)

Description: Parses a JSON string into a Python dictionary or returns it if already parsed.

Parameters:

  • val (str or dict): JSON string or dict.

Example Usage:

parsed = parse_json('{"key": "value"}')

Function: safe_json_loads(*args)

Description: Attempts to parse multiple JSON strings safely and returns the first valid one.

Parameters:

  • *args: Multiple JSON strings.

Example Usage:

config = safe_json_loads("invalid", '{"debug": true}')

Function: dict_to_str(args, sep="&")

Description: Converts a dictionary into a URL query string.

Parameters:

  • args (dict): Dictionary to convert.
  • sep (str): Separator for key-value pairs.

Example Usage:

query = dict_to_str({"name": "Test", "id": 1})

Function: list_to_str(seq, sep=", ")

Description: Converts a list or sequence to a string separated by a given character.

Parameters:

  • seq (list): List of elements.
  • sep (str): Separator.

Example Usage:

joined = list_to_str(["apple", "banana"])

Function: get_safe_filters(filters)

Description: Parses filters provided as JSON and ensures type safety.

Parameters:

  • filters (str): JSON string representing filters.

Example Usage:

safe = get_safe_filters('{"status": "Open"}')

Function: remove_blanks(d)

Description: Removes all keys with falsy values ("", None) from a dictionary.

Parameters:

  • d (dict): Dictionary.

Example Usage:

cleaned = remove_blanks({"name": "", "active": True})

System Information Functions

Function: get_disk_usage()

Description: Returns the disk space used by the files directory of the site.

Parameters: None

Example Usage:

disk_space = get_disk_usage()

Function: get_site_info()

Description: Returns a summary of site-level configuration and usage statistics.

Parameters: None

Example Usage:

info = get_site_info()

Function: get_installed_apps_info()

Description: Retrieves installed apps along with their versions and branches.

Parameters: None

Example Usage:

apps = get_installed_apps_info()

Function: get_bench_path()

Description: Gets the root path of the bench environment.

Parameters: None

Example Usage:

path = get_bench_path()

Decorators and Callback Management

Function: @deprecated

Description: Marks a function as deprecated. Will show warnings when used. Usage:

@deprecated
def old_function():
    pass

Class: CallbackManager

Description: Manages deferred callbacks to run after certain actions like commits. Methods: - add(func): Queue a function. - run(): Run all queued functions. - reset(): Clear the callback queue.

Example Usage:

cb = CallbackManager()
cb.add(lambda: print("Callback"))
cb.run()

Shell Execution Utilities

Function: execute_in_shell(cmd, verbose=False, low_priority=False, check_exit_code=False)

Description: Executes a shell command and returns standard output and error output.

Parameters:

  • cmd (str or list): The shell command to execute.
  • verbose (bool): Print the output if True.
  • low_priority (bool): Run the command with lower priority.
  • check_exit_code (bool): Raise exception if the command fails.

Example Usage:

err, out = execute_in_shell("ls -la", verbose=True)

Function: touch_file(path)

Description: Updates the modification time of a file or creates it if it does not exist.

Parameters:

  • path (str): Path to the file.

Example Usage:

touch_file("temp.log")

JSON & Data Utilities

Function: parse_json(val)

Description: Parses a JSON string into a Python dictionary or returns it if already parsed.

Parameters:

  • val (str or dict): JSON string or dict.

Example Usage:

parsed = parse_json('{"key": "value"}')

Function: safe_json_loads(*args)

Description: Attempts to parse multiple JSON strings safely and returns the first valid one.

Parameters:

  • *args: Multiple JSON strings.

Example Usage:

config = safe_json_loads("invalid", '{"debug": true}')

Function: dict_to_str(args, sep="&")

Description: Converts a dictionary into a URL query string.

Parameters:

  • args (dict): Dictionary to convert.
  • sep (str): Separator for key-value pairs.

Example Usage:

query = dict_to_str({"name": "Test", "id": 1})

Function: list_to_str(seq, sep=", ")

Description: Converts a list or sequence to a string separated by a given character.

Parameters:

  • seq (list): List of elements.
  • sep (str): Separator.

Example Usage:

joined = list_to_str(["apple", "banana"])

Function: get_safe_filters(filters)

Description: Parses filters provided as JSON and ensures type safety.

Parameters:

  • filters (str): JSON string representing filters.

Example Usage:

safe = get_safe_filters('{"status": "Open"}')

Function: remove_blanks(d)

Description: Removes all keys with falsy values ("", None) from a dictionary.

Parameters:

  • d (dict): Dictionary.

Example Usage:

cleaned = remove_blanks({"name": "", "active": True})

System Information Functions

Function: get_disk_usage()

Description: Returns the disk space used by the files directory of the site.

Parameters: None

Example Usage:

disk_space = get_disk_usage()

Function: get_site_info()

Description: Returns a summary of site-level configuration and usage statistics.

Parameters: None

Example Usage:

info = get_site_info()

Function: get_installed_apps_info()

Description: Retrieves installed apps along with their versions and branches.

Parameters: None

Example Usage:

apps = get_installed_apps_info()

Function: get_bench_path()

Description: Gets the root path of the bench environment.

Parameters: None

Example Usage:

path = get_bench_path()

Decorators and Callback Management

Function: @deprecated

Description: Marks a function as deprecated. Will show warnings when used. Usage:

@deprecated
def old_function():
    pass

Class: CallbackManager

Description: Manages deferred callbacks to run after certain actions like commits. Methods: - add(func): Queue a function. - run(): Run all queued functions. - reset(): Clear the callback queue.

Example Usage:

cb = CallbackManager()
cb.add(lambda: print("Callback"))
cb.run()
Discard
Save
Was this article helpful?

On this page

Review Changes ← Back to Content
Message Status Space Raised By Last update on